package com.bbu.javaexam.test;

import lombok.Data;

import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.ReentrantLock;

public class DeadLock {

    /*AQS 原理*/
    static class Mutex extends AbstractQueuedSynchronizer {

        @Override
        protected boolean tryAcquire(int arg) {
            return compareAndSetState(0, 1);
        }

        @Override
        protected boolean tryRelease(int arg) {
            return compareAndSetState(1, 0);
        }

    }


    @Data
    static class Friend {

        private final String name;

        private final ReentrantLock reentrantLock = new ReentrantLock();

        public void method1(Friend f1) {
            reentrantLock.lock();
            System.out.format("对象：%s执行了方法1，接下来应该执行%s的方法2%n", this.name, f1.getName());

            reentrantLock.unlock();
            f1.method2(this);
        }

        public void method2(Friend f1) {
            reentrantLock.lock();
            System.out.format("对象：%s执行了方法2，从%s的方法1中调用的%n", this.name, f1.getName());
            reentrantLock.unlock();
        }
    }

//    public static void main(String[] args) {
//        final Friend friend1 = new Friend("小明");
//        final Friend friend2 = new Friend("小红");
//        new Thread(() -> friend1.method1(friend2)).start();
//        new Thread(() -> friend2.method1(friend1)).start();
//    }

    public static int i = 0;

    public static void main(String[] args) throws InterruptedException {
        Mutex mutex = new Mutex();

        Thread t1 = new Thread(() -> {
            mutex.acquire(0);
            i++;
            mutex.release(0);
        });
        t1.start();
        Thread t2 = new Thread(() -> {
            mutex.acquire(0);
            i++;
            mutex.release(0);
        });
        t2.start();
        t1.join();
        t2.join();
        System.out.println("i:" + i);
    }

}
